import axios from 'axios'
import { ElNotification , ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from '@/utils/ruoyi'
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/stores/user'
import { getServerUrl } from '@/utils'
import router from '@/router'
let logoutFlag = false;

let downloadLoadingInstance;
// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: getServerUrl(),
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['adminToken'] = getToken()
    }
  
    if (config.method === 'get') {
      // 给data赋值以绕过if判断
      config.data = true
    }
    
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log('==request res==', res)
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 401) {
      // 网关验证失败，回到权限平台登录页
      ElMessage({
        message: '登录已失效，请重新登录',
        type: 'error',
        duration: 3 * 1000,
        showClose: true
      })
      location.href = `${location.pathname}#/login`
    } else {
      if (res.errcode !== '0000') {
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.errcode === '0005') {
          if (!logoutFlag) {
            logoutFlag = true
            ElMessageBox.confirm(
              '你已被登出，可以取消继续留在该页面，或者重新登录',
              '登出提示',
              {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              useUserStore().logOut().then(() => {
                console.log('router=====', router)
                router.push('/login')
              })
            })
          }
        } else {
          console.log('-----')
          console.log('报错接口 => ', response.request.responseURL)
          console.log('报错Sequece => ', response.headers.sequence)
          console.log('报错入参 => ', response.config.data)
          console.log('报错信息 => ', res)
          console.log('-----')

          console.log(!document.body.querySelector('.el-message'))
          // if (!document.body.querySelector('.el-message')) {
            ElMessage({
              message: res.errmsg || 'Error',
              type: 'error',
              duration: 3 * 1000,
              showClose: true
            })
          // }
          
        }
        return Promise.reject(res)
      } else {
        return res.result
      }
    }
  },
  error => {
    console.log('==err==' + error) // for debug
    Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      ElMessage.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

export default service
